package com.frxuexi.park2212.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.entity.ParkBean
import com.frxuexi.lib_base.entity.ParkBeanItem
import com.frxuexi.lib_base.entity.Res
import com.frxuexi.lib_base.net.ApiService
import java.lang.Exception

//type:做什么类型的接口查询
class ParkDataSource(val apiService: ApiService, val para: String,val type:String) :
    PagingSource<Int, ParkBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, ParkBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkBeanItem> {
        try {
            //当前页码数
            val page = params.key ?: 1
            var res:Res<ParkBean>?=null
            if(type=="类型") {
                res = apiService.getParksByType(para)
            }else if(type=="状态"){
                res=apiService.getParksByStatus(para)
            }else if(type=="区域"){
                res=apiService.getParksByAreaId(para.toInt())
            }

            val prePage=if(page!=1) page-1 else null
            val nextPage=if(res?.data?.size!=0) page+1 else null
            return LoadResult.Page(res!!.data.sortedByDescending { it.id },prePage,nextPage)
        }catch (e:Exception){
            return LoadResult.Error(e)
        }

    }
}